<template>
  <div>
    <h2>商品列表如下：</h2>
    <div class="row" v-for="(item, index) of goodList" :key="index">
      <div class="row_img">
        <img :src="item.img" />
      </div>
      <div class="row_info">
        <p>商品名称:{{ item.name }}</p>
        <p>商品单价:{{ item.price }}￥</p>
        <button type="button" class="btn" @click="insertCart(index)">
          添加购物车
        </button>
        <button type="button" class="btn1">立即购买</button>
      </div>
    </div>
  </div>
</template>

<script>
// 引入操作仓库的助手函数
import { mapGetters, mapActions } from "vuex";

export default {
    name:"listIndex",
  data() {
    return {
      goodList: [
        {
          id: 1,
          name: "SK2",
          price: 1590.0,
          num: 1,
          img: "http://img13.360buyimg.com/n7/jfs/t1/179804/21/2812/138861/60954151E09f754c1/9706cf7d3f82ce19.jpg",
          status: false,
        },
        {
          id: 2,
          name: "watch",
          price: 1799.9,
          num: 1,
          img: "http://img13.360buyimg.com/n7/jfs/t1/195549/7/1383/147340/609247adE3a47f0f5/bf2a9f6dbd18a0d5.jpg",
          status: false,
        },
        {
          id: 3,
          name: "前男友面膜",
          price: 1059.99,
          num: 1,
          img: "http://img14.360buyimg.com/n7/jfs/t1/181060/34/2821/163555/60954cddE1af45f9c/8f7e11f4fc884da8.jpg",
          status: false,
        },
        {
          id: 4,
          name: "ipad",
          price: 5799,
          num: 1,
          img: "http://img11.360buyimg.com/n7/jfs/t1/161452/24/15900/88869/6063ddfeE258a392b/008f0f5fdb2c4a42.jpg",
          status: false,
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["cartList"]),
  },
  methods: {
    ...mapActions(["addCart"]),
    // 执行添加购物车操作  跳转到购物车页面查看购物车数据详情
    insertCart(index) {
      // 1.执行添加购物车操作
      /**
             * 思路：
             *  1.获取到要添加到购物车中的数据
                2.获取到当前仓库中所有的购物车数据
                3.将上次的购物车数据和本次要添加的数据进行合并
             */
      let insertRow = this.goodList[index];
      // console.log(insertRow)
      // console.log(this.cartList)
      // let newData = [insertRow, ...this.cartList]//[{},{},{},{}]
      // this.$store.dispatch('addCart', newData)
      this.addCart([insertRow, ...this.cartList]);

      this.$router.push("/cart");
      // 2.跳转到购物车页面查看购物车数据详情
    },
  },
};
</script>

<style scoped>
.row {
  display: flex;
  justify-content: space-around;
  align-items: center;
  border: 2px solid orangered;
}

.row_img img {
  width: 100px;
  height: 100px;
}
.btn {
  width: 100px;
  height: 40px;
  background-color: #d9534f;
  /* outline: none; */
  border: 0;
  border-radius: 5px;
  color: white;
}
.btn1 {
  width: 100px;
  height: 40px;
  background-color: #f0ad4e;
  /* outline: none; */
  border: 0;
  border-radius: 5px;
  color: white;
}
</style>
